<template>
  <div id="oc-form">
    <component :is="'el-form'" v-bind="props.form">
      <template v-for="item in props.columns" :key="item.item.prop">
        <component :is="'el-form-item'" v-bind="item.item">
          <component :is="`el-${item.attr.type}`" v-bind="item.attr.prop" v-model="nowModel[item.item.prop]">
            <template v-if="item.attr.type === 'select'">
              <component
                :is="`el-option`"
                v-for="(col, index) in getEnum"
                :key="index"
                :label="col.label"
                :value="col.value"
              ></component>
            </template>
            <template v-if="item.attr.type === 'radio-group'">
              <component :is="'el-radio'" v-for="(col, index) in getEnum" :key="index" :label="col.value">{{
                col.label
              }}</component>
            </template>
          </component>
        </component>
      </template>
    </component>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { FormProps } from "element-plus";
import type { OCForm } from "./interface/index";
import { ResultData } from "@/api/interface";
interface Props {
  form?: FormProps;
  columns?: OCForm.FormColumn[];
  model?: any;
}
const nowModel = ref<any>();
watch(
  () => props.model,
  () => {
    nowModel.value = props.model;
  },
  { deep: true, immediate: true }
);
const props = withDefaults(defineProps<Props>(), {});
const getEnum = async (fn: () => Promise<ResultData<any>>, item: OCForm.FormColumn) => {
  const { data } = await fn();
  if (!data && !data.length) return [];
  let list = [];
  for (let i = 0; i < data.length; i++) {
    list.push({
      label: data[i][item.config.fieldName.label],
      value: data[i][item.config.fieldName.value],
      children: data[i][item.config.fieldName.children]
    });
  }
  return list;
};
</script>

<style></style>
